// pages/user_end/order_choose/order_choose.js
const app = getApp();
const request = require('../../../utils/request.js');
const url = require('../../../utils/url.js');
const util = require('../../../utils/util.js');
const cookie = require('../../../utils/cookie.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 1,
    show1: false,
    show2: false,
    cost: '',
    nindex: 0,
    index: 1,
    id: 0,
    order: {},
    show3: false,
    datelist: [],
    timelist: [],
    active: '',
    reserveDate: "",
    isReserve: 0,
    cnum: 0,
  },
  close1() {
    this.setData({
      show1: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id: options.id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;
	
    cookie.getCookie('userInfo', function (res) {
      if (res) {
        var etime = Date.parse(new Date()) / 1000;
        
        if (etime < res.expiretime) {
          that.setData({
            login: 1,
            token: res.token
          })
          that.getDatelist();
          that.getOrder();
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  makeCall(e){
	   var phone = e.currentTarget.dataset.phone;
	   // wx.makePhoneCall({
	   //   phoneNumber: phone,
	   // })
	   wx.showToast({
	     title: phone,
	     icon: 'none'
	   });
	      wx.makePhoneCall({
	        phoneNumber: phone,
	        success: function() {
	          console.log('Call Success');
	        },
	        fail: function() {
	          console.log('Call Fail');
	        }
	      });
  },
  reorder(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../payorder/payorder?id=' + id
    })
  },
  goComment(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../leave_comment/leave_comment?id=' + id
    })
  },
  gorefund(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../refund/refund?id=' + id
    })
  },
  getDatelist: function () {
    var that = this;
    let param = {
      scoure: 'wxapp',
      token: that.data.token
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.getdatelist, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if (res.data.code == 1) {
        that.setData({
          datelist: res.data.data,
          reserveDate: res.data.data[0].date
        })
      }
    })
  },
  getTimelist: function () {
    var that = this;
    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      order_id: that.data.orderId,
      date: that.data.reserveDate,
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.getordertimelist, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if (res.data.code == 1) {
        that.setData({
          timelist: res.data.data.timelist,
          show1: true,
          service_multiple: res.data.data.multiple
        })
      }
    })
  },
  showTime(e) {
    var that = this;
    that.setData({
      orderId: that.data.id
    })
    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      order_id: that.data.orderId,
      date: that.data.reserveDate,
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.getordertimelist, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if (res.data.code == 1) {
        that.setData({
          timelist: res.data.data.timelist,
          show1: true,
          service_multiple: res.data.data.multiple
        })
      }
    })
  },
  choseReserve(e) {
    var time = e.currentTarget.dataset.timestamp;
    var check = e.currentTarget.dataset.checked;
    if (check == 0) {
      wx.showToast({
        title: '当前时间不可选',
        icon: 'none'
      });
      return false;
    }
    //遍历可选时间
    var that = this;
    var showtips = 0;
    //判断单选方式
    if (that.data.service_multiple == false) {
      that.data.timelist.forEach((item, index) => {
        var sItem = "timelist[" + index + "].active";
        if (item.timestamp == time) {
          that.setData({
            [sItem]: 1,
          });
        } else {
          that.setData({
            [sItem]: 0,
          });
        }
      })
    } else {
      var count = 0;
      var length = that.timelist.length - 1;
      var arrIds = [];
      that.data.timelist.forEach((item, index) => {
        if (item.active == 1) {
          count++;
          arrIds.push(index);
        }
      });

      that.data.timelist.forEach((item, index) => {
        if (item.timestamp == time) {
          if (item.active == 1) {
            var active = 0;
            //判断连续性
            if (count > 0) {
              if (index == arrIds[0]) {
                var active = 0;

              } else if (index == arrIds[count - 1]) {
                var active = 0;

              } else {
                var active = 1;
                showtips = 2;
              }
            }

          } else {
            var active = 1;
            //判断连续性
            if (count > 0) {
              if (index == 0) {
                if (that.data.timelist[index + 1].active == 1) {
                  var active = 1;
                } else {
                  showtips = 1;
                  var active = 0;
                }
              } else if (index == length) {
                if (that.data.timelist[index - 1].active == 1) {
                  var active = 1;
                } else {
                  showtips = 1;
                  var active = 0;
                }
              } else {
                if (that.data.timelist[index + 1].active == 1 || that.data.timelist[index - 1].active == 1) {
                  var active = 1;
                } else {
                  showtips = 1;
                  var active = 0;
                }
              }
            }

          }
          var sItem = "timelist[" + index + "].active";
          that.setData({
            [sItem]: active
          })
        }
      })
    }
    if (showtips == 1) {
      wx.showToast({
        title: '请先选择连续的时间!',
        icon: "none"
      })
    }
    if (showtips == 2) {
      wx.showToast({
        title: '请先选择取消开始时间!',
        icon: "none"
      })
    }
    //选择结果
    var chose = 0;
    var arrayIds = [];
    that.data.timelist.forEach((item, index) => {
      if (item.active == 1) {
        chose++;
        arrayIds.push(index);
      }
    });
    that.setData({
      cnum: chose
    })
    if (chose == 0) {
      that.setData({
        isReserve: 0,
        reserveShow: '',
        reserveTime: ''
      })
    } else {
      that.setData({
        isReserve: 1,
        reserveShow: that.data.reserveDate + ' ' + that.data.timelist[arrayIds[0]].start_time,
        reserveTime: that.data.timelist[arrayIds[0]].timestamp
      })
    }
  },
  chooseDateNav(e) {
    this.setData({
      nindex: e.currentTarget.dataset.current,
      reserveDate: e.currentTarget.dataset.date,
      isReserve: 0,
      reserveShow: "",
      reserveTime: ""
    })
    this.getTimelist();
  },
  getOrder: function () {       
    var that = this;
    let param = {
      id: that.data.id,
      token: that.data.token
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.orderdetail, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      that.setData({
        order: res.data.data
      })
      if (res.data.data.bargain == 1) {
        //议价
        that.setData({
          index: 2,
          cost: ''
        })
      } else {   
        that.setData({
          index: 1
        })
      }
    })

  },
  goDetail(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../order_choose/order_choose?id=' + id
    })
  },
  updateTime() {
    var that = this;
    if (!that.data.isReserve) {
      wx.showToast({
        title: "请选择时间!",
        icon: "loading"
      })
      return false;
    }
    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      service_start_time: that.data.reserveTime,
      service_num: that.data.cnum,
      id: that.data.id,
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.changeordertime, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      wx.showToast({
        title: res.data.msg,
        icon: "none"
      })
      that.setData({
        show1: false
      })
      if (res.data.code == 1) {
        that.setData({
          currentPage: 1,
          reserveTime: '',
          isReserve: 0,
          cnum: 0
        })
        that.getOrder();
      }
    })
  },
  cancelOrder(e) {
    var id = e.currentTarget.dataset.id;
    var that = this;
    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      id: id
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.cancelorder, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      wx.showToast({
        title: res.data.msg,
        icon: "none"
      })
      if (res.data.code == 1) {
        that.setData({
          page: 1,
        })
        that.getOrder();
      }
    })
  },
  finishOrder(e) {
    var id = e.currentTarget.dataset.id;
    var that = this;
    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      id: id
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.finishorder, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      wx.showToast({
        title: res.data.msg,
        icon: "none"
      })
      if (res.data.code == 1) {
        that.setData({
          page: 1,
        })
        that.getOrder();
      }
    })
  },
  cancelrefund(e) {
    var id = e.currentTarget.dataset.id;
    var that = this;
    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      id: id
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.cancelrefund, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      wx.showToast({
        title: res.data.msg,
        icon: "none"
      })
      if (res.data.code == 1) {
        that.setData({
          page: 1,
        })
        that.getOrder();
      }
    })
  },
  payOrder(e) {
    var id = e.currentTarget.dataset.id;
    var that = this;
    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      id: id
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.payorder, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if (res.data.code == 1) {
        //直接支付成功
        //跳转订单详情页
        let orderId = res.data.data.id;
        if (res.data.data.pay_money > 0) {
          var config = JSON.parse(res.data.data.wxconfig);
          console.log("成功", JSON.parse(res.data.data.wxconfig));
          wx.requestPayment({
            'timeStamp': config.timestamp,
            'nonceStr': config.nonceStr,
            'package': config.package,
            'signType': config.signType,
            'paySign': config.paySign,
            'success': function (res2) {
              console.log("成功", res2)
              if (res2.errMsg == 'requestPayment:ok') {
                wx.redirectTo({
                  url: '/pages/user_end/order/order',
                })
                return false;
              }
            },
            'fail': function (res2) {
              console.log("失败", res2)
              wx.navigateTo({
                url: '../order_choose/order_choose?id=' + orderId,
              })
              return false;
            },
            'complete': function (res2) {}
          })
        } else {
          wx.showToast({
            title: '支付成功',
            icon: 'none'
          })
          wx.redirectTo({
            url: '/pages/user_end/order/order',
          })
          return false;
        }
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  payconfig(e) {
    var id = e.currentTarget.dataset.id;
    var that = this;
    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      id: id
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.payconfig, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if (res.data.code == 1) {
        //直接支付成功
        //跳转订单详情页
        let orderId = res.data.data.id;
        if (res.data.data.pay_money > 0) {
          var config = JSON.parse(res.data.data.wxconfig);
          console.log("成功", JSON.parse(res.data.data.wxconfig));
          wx.requestPayment({
            'timeStamp': config.timestamp,
            'nonceStr': config.nonceStr,
            'package': config.package,
            'signType': config.signType,
            'paySign': config.paySign,
            'success': function (res2) {
              console.log("成功", res2)
              if (res2.errMsg == 'requestPayment:ok') {
                wx.navigateTo({
                  url: '../order_choose/order_choose?id=' + orderId,
                })
                return false;
              }
            },
            'fail': function (res2) {
              console.log("失败", res2)
              wx.navigateTo({
                url: '../order_choose/order_choose?id=' + orderId,
              })
              return false;
            },
            'complete': function (res2) {}
          })
        } else {
          wx.showToast({
            title: '支付成功',
            icon: 'none'
          })
          wx.navigateTo({
            url: '../order_choose/order_choose?id=' + orderId,
          })
          return false;
        }
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  checkNoOrder(e) {
    var id = e.currentTarget.dataset.id;
    var that = this;
    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      id: id
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.checknoorder, param, url.REQUEST_METHOD_POST).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      wx.showToast({
        title: res.data.msg,
        icon: "none"
      })
      if (res.data.code == 1) {
        that.setData({
          page: 1,
        })
        that.getOrder();
      }
    })
  }, 
})